import { install } from "./install";

export default class VueRouter {
  constructor({ routes }) {
    // 接受参数routes
    let routerMap = Object.create(null);
    routes.map((route) => {
      let path = route.path;
      routerMap[path] = route;
    });
    this.routerMap = routerMap;
    console.log("this.routerMap", this.routerMap);
    //
    this.current = {
      path: "/",
      component: {
        template: "<div></div>",
      },
    };
    // 执行listener
    this.listener();
  }
  listener() {
    // 初次加载监听
    window.addEventListener("load", () => {
      let hash = window.location.hash;
      if (!hash) {
        window.location.hash = "#/";
      }
      let route = this.findHash(hash.slice(1));
      if(route) {
        this.current.path = route.path;
        this.current.component = route.component;
      }
    });
    // 监听hash改变
    window.addEventListener("hashchange", () => {
      let hash = window.location.hash;
      let route = this.findHash(hash.slice(1));
      if(route) {
        this.current.path = route.path;
        this.current.component = route.component;
      }
    });
  }
  findHash(path) {
    if (this.routerMap[path]) {
      return this.routerMap[path];
    }
    return null;
  }
}
// 注册方法
VueRouter.install = install;
// 注册Router
if (window.Vue) {
  window.Vue.use(VueRouter);
}
